import os

def process_camera_files(input_folder, output_file, endFile):
    # 用于存储已处理的 CAMERA_ID
    seen_camera_ids = set()
    
    # 用于存储合并的行
    merged_lines = []

    # 使用 os.walk 遍历所有子文件夹和文件
    for root, _, files in os.walk(input_folder):
        for filename in files:
            # 只处理 camera.txt 文件
            if filename == endFile:
                file_path = os.path.join(root, filename)
                
                with open(file_path, 'r') as f:
                    for line in f:
                        # 跳过空行
                        if not line.strip():
                            continue
                        
                        # 分割行并获取 CAMERA_ID
                        parts = line.split()
                        camera_id = parts[0]
                        
                        # 如果 CAMERA_ID 尚未处理过，添加到集合和合并列表中
                        if camera_id not in seen_camera_ids:
                            seen_camera_ids.add(camera_id)
                            merged_lines.append(line)
    
    # 将合并后的内容写入输出文件
    with open(output_file, 'w') as f_out:
        f_out.writelines(merged_lines)
        print(f"合并完成，结果已保存到 {output_file}")

def merge_images_txt(root_dir, output_file):
    with open(output_file, 'w') as outfile:
        for subdir, _, files in os.walk(root_dir):
            for file in files:
                if file == "points3D.txt":
                    file_path = os.path.join(subdir, file)
                    with open(file_path, 'r') as infile:
                        # 读取每一行并跳过以 # 开头的行
                        for line in infile:
                            if not line.startswith('#'):  # 只写入不以 # 开头的行
                                outfile.write(line)


# 使用函数：指定输入文件夹和输出文件路径
input_folder = "C:\\WorkOut\\Code\\3DGS\\Data\\MinorCitySeg\\dense"  # 替换为实际输入文件夹路径
output_file = "C:\\WorkOut\\Code\\3DGS\\Data\\MinorCitySeg\\dense\\merged_point.txt"  # 替换为实际输出文件路径

# 合并文件
#process_camera_files(input_folder, output_file, "cameras.txt")
merge_images_txt(input_folder, output_file)
